﻿using AutoMapper;
using B.S.BaseData.Api.Write.Application.Command.Sale;
using B.S.BaseData.Domain;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using MediatR;
using SmartTracking.Domain.ZXL;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Sale
{
    public class CreateSaleCommandHandler : IRequestHandler<CreateSaleCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Sales> _saleRepository;
        private readonly IBaseRepository<Saleshead> _salehead;
        private readonly IMapper map;

        public CreateSaleCommandHandler(IBaseRepository<Sales> saleRepository, IMapper map, IBaseRepository<Saleshead> salehead)
        {
            _saleRepository = saleRepository;
            this.map = map;
            _salehead = salehead;
        }

        public async Task<ApiResult<int>> Handle(CreateSaleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            Saleshead salehead = new Saleshead();

            salehead.SalesDate = request.SalesDate;
            salehead.Customer = request.Customer;
            salehead.Salesperson = request.Salesperson;
            salehead.Department = request.Department;
            salehead.Warehouse = request.Warehouse;
            salehead.Shippingaddress = request.Shippingaddress;
            salehead.Documentnumber = request.Documentnumber;
            salehead.Serialnumber = request.Serialnumber;

            await _salehead.AddAsync(salehead);

            int r = await _saleRepository.AddRangeAsync(request.SalesList);

            if (r == 0)
            {
                res.Message = "创建销售失败";
                res.Code = ApiEnum.新增失败;
            }
            else
            {
                res.Message = "创建销售成功";
                res.Code = ApiEnum.新增成功;
            }

            return await Task.FromResult(res);

        }
    }
}
